import { GetCookie } from "./utils.js";
import { InitHeader } from "./header.js";

async function GetRecords(access_token, page, page_size) {
  const url = `http://localhost:9966/user/records?access_token=${encodeURIComponent(
    access_token
  )}&page=${page}&page_size=${page_size}`;

  try {
    const response = await fetch(url, { method: "GET" });
    if (!response.ok) {
      throw new Error("获取记录失败");
    }
    const data = await response.json();
    console.log(data);
    if (data.retcode !== 0) {
      throw new Error(data.message || "获取记录失败");
    }
    OnGetRecords(data); // 调用处理记录的函数
  } catch (error) {
    console.error("Error fetching records:", error);
    alert("获取记录失败，请稍后再试");
  }
}

var status_list = {
  0: "正常",
  1: "已签到",
  2: "已签退",
  100: "迟到",
  101: "早退",
  102: "缺勤",
};

var cur_page = 1; // 当前页码
const page_size = 10; // 每页记录数

function AddOneRecord(element, record) {
  var status_str = status_list[record.state] || "异常";
  const date = new Date(record.date * 1000);
  const date_string = `${date.getFullYear()}-${String(
    date.getMonth() + 1
  ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
  const signin_time_str =record.signin_time ? new Date(record.signin_time * 1000).toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
  }) : '-'; // 如果没有签到时间，显示为 '-'
  const signout_time_str = record.signout_time ? new Date(record.signout_time * 1000).toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
  }) : '-'; // 如果没有签退时间，显示为 '-'

  var duration = '-'; // 默认值
  if (record.signin_time && record.signout_time) {
    const duration_seconds = record.signout_time - record.signin_time;
    const hours = Math.floor(duration_seconds / 3600);
    const minutes = Math.floor((duration_seconds % 3600) / 60);
    const seconds = duration_seconds % 60;
    // 格式化时长为 HH:mm:ss
    duration = `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
  }

  const listItem = document.createElement("tr");
  var date_cell = document.createElement("td");
  date_cell.textContent = date_string;
  listItem.appendChild(date_cell);

  var status_cell = document.createElement("td");
  status_cell.textContent = status_str;
  var status_class = "text-secondary";
  switch (record.state) {
    case 0:
      status_class = "text-secondary";
      break;
    case 1:
      status_class = "text-primary";
      break;
    case 2:
      status_class = "text-success";
      break;
    case 100:
    case 101:
    case 102:
      status_class = "text-danger";
      break;
  }
  status_cell.classList.add(status_class);
  listItem.appendChild(status_cell);

  var signin_cell = document.createElement("td");
  signin_cell.textContent = signin_time_str;
  listItem.appendChild(signin_cell);

  var signout_cell = document.createElement("td");
  signout_cell.textContent = signout_time_str;
  listItem.appendChild(signout_cell);

  var duration_cell = document.createElement("td");
  duration_cell.textContent = duration;
  listItem.appendChild(duration_cell);

  element.appendChild(listItem);
}

async function OnGetRecords(data) {
  const recordList = document.getElementById("record-list");
  recordList.innerHTML = ""; // 清空现有记录

  if (data.records && data.records.length > 0) {
    data.records.forEach((record) => {
      AddOneRecord(recordList, record);
    });
  } else {
    recordList.innerHTML =
      "<tr><td colspan='5' class='text-secondary text-center mt=3'>暂无记录</td></tr>";
  }
}

document.addEventListener("DOMContentLoaded", () => {
  const access_token = GetCookie("access_token");
  if (!access_token) {
    alert("请先登录");
    window.location.href = "/index.html"; // 如果没有登录，重定向到登录页面
    return;
  }

  // 获取记录
  GetRecords(access_token, cur_page, page_size); // 默认获取第一页，10条记录
  document.getElementById("prev_page").addEventListener("click", () => {
    if (cur_page > 1) {
      cur_page--;
      GetRecords(access_token, cur_page, page_size);
      document.getElementById("current_page").textContent = cur_page;
    }
  });
  document.getElementById("next_page").addEventListener("click", () => {
    cur_page++;
    GetRecords(access_token, cur_page, page_size);
    document.getElementById("current_page").textContent = cur_page;
  });
  document.getElementById("current_page").textContent = cur_page;
});